package com.xwj.controller.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageInfo;
import com.xwj.Enums.StatusInfoEnum;
import com.xwj.data.StaticData;
import com.xwj.dto.OrderInfoDto;
import com.xwj.entity.OrderDetailEntity;
import com.xwj.entity.RaOrder;
import com.xwj.service.Impl.RaOrderServiceImpl;
import com.xwj.service.Impl.RaStatusInfoServiceImpl;
import com.xwj.service.holder.RaRegisterUserHolder;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/order/")
public class OrderController {

    @Autowired
    private RaOrderServiceImpl raOrderService;
    @Autowired
    private RaStatusInfoServiceImpl raStatusInfoService;

    @RequestMapping(value = "orderInfoList")
    public ModelAndView orderInfoList(ModelAndView modelAndView) {
        String label = StatusInfoEnum.OrderInfo.getName();
        modelAndView.addObject("orderStatus", raStatusInfoService.findStatusByLabel(label));
        modelAndView.setViewName("/admin/order/orderInfo");
        return modelAndView;
    }

    /**
     * 显示或查询
     *
     * @param pageIndex
     * @param pageSize
     * @param key
     * @return
     */
    @RequestMapping(value = "orderInfoDetail", method = RequestMethod.POST)
    public Map<String, Object> orderInfoList(@RequestParam(value = "page") Integer pageIndex,
                                             @RequestParam(value = "limit") Integer pageSize,
                                             @RequestParam(value = "key", required = false) String key) {
        PageInfo<RaOrder> page;
        OrderInfoDto orderInfoDto = null;
        if (key != null) orderInfoDto = JSON.parseObject(key, new TypeReference<OrderInfoDto>() {
        });
        if (orderInfoDto == null)
            page = raOrderService.findAllOrderWithPage(pageIndex, pageSize);
        else
            page = raOrderService.findOrderByPropertyWithPage(pageIndex, pageSize, orderInfoDto);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", page.getTotal());
        map.put("data", page.getList());
        return map;
    }

    /**
     * 添加
     *
     * @param raOrder
     * @return
     */
    @RequestMapping(value = "addOneOrder", method = RequestMethod.POST)
    public Map<String, Object> addOneOrder(RaOrder raOrder, OrderDetailEntity orderDetailEntity) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(raOrder.getLandlordId()) && !RaRegisterUserHolder.hasUser(raOrder.getLandlordId())) {
            map.put("msg", "无此用户:" + raOrder.getLandlordId());
            return map;
        }
        if (StringUtils.isNotBlank(raOrder.getTenantId()) && !RaRegisterUserHolder.hasUser(raOrder.getTenantId())) {
            map.put("msg", "无此用户:" + raOrder.getTenantId());
            return map;
        }
        if (orderDetailEntity.getLongRent().equals(StaticData.LONG_TIME_STR) && orderDetailEntity.getLease() < StaticData.LONG_TIME_RENT_LEASE) {
            map.put("msg", "长租期限必须多于等于" + StaticData.LONG_TIME_RENT_LEASE + "个月");
            return map;
        }
        String expireTime = DateTime.parse(orderDetailEntity.getEffectTime(), DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"))
                .plusMonths(orderDetailEntity.getLease()).toString("yyyy-MM-dd HH:mm:ss");
        orderDetailEntity.setExpireTime(expireTime);
        String detail = JSON.toJSONString(orderDetailEntity);
        raOrder.setDetailInfo(detail);
        if (raOrderService.addOneOrder(raOrder) > 0)
            map.put("msg", "添加成功");
        else
            map.put("msg", "添加失败");
        return map;
    }

    /**
     * 更新属性
     *
     * @param orderInfoDto
     * @return
     */
    @RequestMapping(value = "updateProperty", method = RequestMethod.POST)
    public Map<String, Object> updateProperty(OrderInfoDto orderInfoDto) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(orderInfoDto.getLandlordId()) && !RaRegisterUserHolder.hasUser(orderInfoDto.getLandlordId())) {
            map.put("msg", "无此用户:" + orderInfoDto.getLandlordId());
            return map;
        }
        if (StringUtils.isNotBlank(orderInfoDto.getTenantId()) && !RaRegisterUserHolder.hasUser(orderInfoDto.getTenantId())) {
            map.put("msg", "无此用户:" + orderInfoDto.getTenantId());
            return map;
        }
        if (raOrderService.updateProperty(orderInfoDto) > 0)
            map.put("msg", "更新成功");
        else
            map.put("msg", "更新失败");
        return map;
    }

    /**
     * 更新详情
     *
     * @param id
     * @param orderDetailEntity
     * @return
     */
    @RequestMapping(value = "updateDetail", method = RequestMethod.POST)
    public Map<String, Object> updateDetail(String id, OrderDetailEntity orderDetailEntity) {
        Map<String, Object> map = new HashMap<>();
        if (orderDetailEntity.getLongRent().equals(StaticData.LONG_TIME_STR) && orderDetailEntity.getLease() < StaticData.LONG_TIME_RENT_LEASE) {
            map.put("msg", "长租期限必须多于等于" + StaticData.LONG_TIME_RENT_LEASE + "个月");
            return map;
        }
        String expireTime = DateTime.parse(orderDetailEntity.getEffectTime(), DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"))
                .plusDays(orderDetailEntity.getLease()).toString("yyyy-MM-dd HH:mm:ss");
        orderDetailEntity.setExpireTime(expireTime);
        if (raOrderService.updateDetail(id, orderDetailEntity) > 0)
            map.put("msg", "订单详情更新成功");
        else
            map.put("msg", "订单详情更新失败");
        return map;
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "deleteById", method = RequestMethod.POST)
    public Map<String, Object> deleteById(@RequestParam(value = "id") String id) {
        Map<String, Object> map = new HashMap<>();
        List<String> ids = new ArrayList<>();
        ids.add(id);
        if (raOrderService.deleteByIds(ids) > 0)
            map.put("msg", "删除成功");
        else
            map.put("msg", "数据有误，删除失败");
        return map;
    }

    /**
     * 批量删除
     *
     * @param mydata
     * @return
     */
    @RequestMapping(value = "deleteBatchById", method = RequestMethod.POST)
    public Map<String, Object> deleteBatchById(@RequestParam(value = "mydata", required = false) String mydata) {
        Map<String, Object> map = new HashMap<>();
        List<RaOrder> raOrderList = JSON.parseArray(mydata, RaOrder.class);
        if (raOrderList.size() == 0) {
            map.put("msg", "未选中任何选项");
            return map;
        }
        List<String> ids = raOrderService.parseListId(raOrderList);
        if (raOrderService.deleteByIds(ids) > 0)
            map.put("msg", "删除成功");
        else
            map.put("msg", "数据操作异常");
        return map;
    }

}
